//
// Copyright 2010 Marcel Urbanek
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//      http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package de.urbiworx.typewriter;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import de.urbiworx.typewriter.FoJsfOutputStream.PdfResult;

public class FoPhaseListener implements PhaseListener {
	Logger logger=Logger.getLogger("de.urbiworx.typewriter");
	public void afterPhase(PhaseEvent phaseEvent) {
	}

	public void beforePhase(PhaseEvent phaseEvent) {
		FacesContext context=FacesContext.getCurrentInstance();
		Map<String,Object> session=context.getExternalContext().getSessionMap();
		if (session.containsKey(FoJsfOutputStream.TYPEWRITER_RESULT)){
			HttpServletRequest request=((HttpServletRequest)context.getExternalContext().getRequest());
			HttpServletResponse response=((HttpServletResponse)context.getExternalContext().getResponse());
			if (!session.get(FoJsfOutputStream.TYPEWRITER_URL).toString().equals(request.getRequestURL().toString())){
				session.remove(FoJsfOutputStream.TYPEWRITER_RESULT);
				return;
			}
			FoJsfOutputStream.PdfResult result=(PdfResult) session.get(FoJsfOutputStream.TYPEWRITER_RESULT);
			 OutputStream stream;
			try {
				stream = response.getOutputStream();
				response.setContentType(result.contentType);
				stream.write(result.content);
			} catch (IOException e1) {
				logger.log(Level.WARNING,"Error while trying to write PDF response to outputstream" , e1);
			}
			context.responseComplete();
			session.remove(FoJsfOutputStream.TYPEWRITER_RESULT);
		}
		
	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
}
